package com.proxy.scanandcheck.common.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IPUtil {
	
	private static final String AClassStartIp = "1.0.0.1";
	private static final String AClassEndIp = "126.255.255.254";
	
//	private static final String AClassStartIp = "209.160.66.215";
//	private static final String AClassEndIp = "209.160.66.230";
	//209.160.66.215:8080
	
	private static final String BClassStartIp = "128.0.0.1";
	private static final String BClassEndIp = "191.255.255.254";
	
	private static final String CClassStartIp = "192.0.0.1";
	private static final String CClassEndIp = "223.255.255.255";
	
    public static long ip2Long(String strIP){
        long[] ip=new long[4]; 
        int position1=strIP.indexOf("."); 
        int position2=strIP.indexOf(".",position1+1); 
        int position3=strIP.indexOf(".",position2+1); 
        ip[0]=Long.parseLong(strIP.substring(0,position1)); 
        ip[1]=Long.parseLong(strIP.substring(position1+1,position2)); 
        ip[2]=Long.parseLong(strIP.substring(position2+1,position3)); 
        ip[3]=Long.parseLong(strIP.substring(position3+1)); 
        return (ip[0]<<24)+(ip[1]<<16)+(ip[2]<<8)+ip[3]; 
   }
    
   public static String long2IP(long longIP){ 
        StringBuffer sb=new StringBuffer(""); 
        sb.append(String.valueOf(longIP>>>24)); 
        sb.append(".");         
        sb.append(String.valueOf((longIP&0x00FFFFFF)>>>16)); 
        sb.append("."); 
        sb.append(String.valueOf((longIP&0x0000FFFF)>>>8)); 
        sb.append("."); 
        sb.append(String.valueOf(longIP&0x000000FF)); 
        return sb.toString(); 
   }
   
   public static boolean isPrivateIp(String ip)
	{
		String regex = "(^127\\.0\\.0\\.1)|" +
						"(^10\\..*)|" +
						"(^172\\.1[6-9]\\..*)|" +
						"(^172\\.2[0-9]\\..*)|" +
						"(^172\\.3[0-1]\\..*)|" +
						"(^192\\.168\\..*)";
		
		Pattern pattern = Pattern.compile(regex);  
	    Matcher matcher = pattern.matcher(ip);
		return matcher.matches();
	}
   
   public static void main(String args [])
   {
	   String ip = "192.168.1.108";
	   long ipLong = 3232235884l; //192.168.1.108
	   long ipLongOther = 3232236884l;
	   System.out.println(ip2Long(AClassStartIp));
	   System.out.println(ip2Long(AClassEndIp));
	   System.out.println(ip2Long(BClassStartIp));
	   System.out.println(ip2Long(BClassEndIp));
	   System.out.println(ip2Long(CClassStartIp));
	   System.out.println(ip2Long(CClassEndIp));
	   System.out.println(long2IP(ipLongOther));
	   
	   System.out.println(ip2Long("68.3.145.212") - ip2Long("68.3.141.212"));
	   System.out.println();
	    
   }
   
   

}
